package com.simon.jkxj.ui.consultation

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.simon.jkxj.R
import com.simon.jkxj.databinding.ActivityChatBinding
import de.hdodenhof.circleimageview.CircleImageView
import java.text.SimpleDateFormat
import java.util.*

class ChatActivity : AppCompatActivity() {

    private lateinit var binding: ActivityChatBinding
    private val messages = mutableListOf<Message>()
    private lateinit var chatAdapter: MessageAdapter
    private lateinit var doctorAvatarName: String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityChatBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val doctorName = intent.getStringExtra("doctorName") ?: "医生"
        doctorAvatarName = intent.getStringExtra("doctorAvatar") ?: ""

        setupToolbar(doctorName)
        setupChatRecyclerView()
        setupSendMessageButton()

        // Load static messages for demo
        loadStaticMessages()
    }

    private fun setupToolbar(doctorName: String) {
        binding.toolbar.title = doctorName
        binding.toolbar.setNavigationOnClickListener {
            onBackPressed()
        }
    }

    private fun setupChatRecyclerView() {
        chatAdapter = MessageAdapter(messages, doctorAvatarName)
        binding.recyclerViewChat.layoutManager = LinearLayoutManager(this)
        binding.recyclerViewChat.adapter = chatAdapter
    }

    private fun setupSendMessageButton() {
        binding.buttonSend.setOnClickListener {
            val messageText = binding.editTextMessage.text.toString().trim()
            if (messageText.isNotEmpty()) {
                val newMessage = Message(
                    id = UUID.randomUUID().toString(),
                    senderId = "user001", // Static user ID for demo
                    receiverId = intent.getStringExtra("doctorId") ?: "",
                    content = messageText,
                    timestamp = System.currentTimeMillis(),
                    type = "text"
                )
                messages.add(newMessage)
                chatAdapter.notifyItemInserted(messages.size - 1)
                binding.recyclerViewChat.scrollToPosition(messages.size - 1)
                binding.editTextMessage.text.clear()

                // Show typing indicator
                binding.textTypingIndicator.visibility = View.VISIBLE

                // Simulate doctor's reply after a short delay
                binding.recyclerViewChat.postDelayed({ simulateDoctorReply() }, 1500)
            }
        }
    }

    private fun loadStaticMessages() {
        messages.add(Message("msg001", "d001", "user001", "你好，请问有什么可以帮助您的？", System.currentTimeMillis() - 60000, "text"))
        messages.add(Message("msg002", "user001", "d001", "医生，我最近总是咳嗽，咳痰，而且感觉胸闷。", System.currentTimeMillis() - 30000, "text"))
        messages.add(Message("msg003", "d001", "user001", "好的，我了解了。这些症状持续多久了？有没有发热、喘息等其他症状？", System.currentTimeMillis() - 10000, "text"))
        chatAdapter.notifyDataSetChanged()
        binding.recyclerViewChat.scrollToPosition(messages.size - 1)
    }

    private fun simulateDoctorReply() {
        // Hide typing indicator first
        binding.textTypingIndicator.visibility = View.GONE

        val lastUserMessage = messages.lastOrNull { it.senderId == "user001" }?.content ?: ""

        val reply = when {
            lastUserMessage.contains("咳嗽") || lastUserMessage.contains("咳痰") -> "根据您描述的症状，我建议您多休息，避免辛辣刺激食物。必要时可以服用一些止咳化痰的药物。"
            lastUserMessage.contains("胸闷") || lastUserMessage.contains("气短") -> "胸闷和气短需要引起重视。请问您有没有去医院检查过？"
            lastUserMessage.contains("你好") -> "您好，请问有什么可以帮助您的？"
            else -> "好的，我明白了。请您再说具体一些，以便我更好地为您提供建议。"
        }

        val doctorReply = Message(
            id = UUID.randomUUID().toString(),
            senderId = intent.getStringExtra("doctorId") ?: "",
            receiverId = "user001",
            content = reply,
            timestamp = System.currentTimeMillis(),
            type = "text"
        )
        messages.add(doctorReply)
        chatAdapter.notifyItemInserted(messages.size - 1)
        binding.recyclerViewChat.scrollToPosition(messages.size - 1)
    }
}

// 消息数据类 (简化版，用于Demo)
data class Message(
    val id: String,
    val senderId: String,
    val receiverId: String,
    val content: String,
    val timestamp: Long,
    val type: String
)

class MessageAdapter(private val messages: List<Message>, private val doctorAvatarName: String) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private val VIEW_TYPE_MESSAGE_SENT = 1
    private val VIEW_TYPE_MESSAGE_RECEIVED = 2

    override fun getItemViewType(position: Int): Int {
        return if (messages[position].senderId == "user001") { // Assuming "user001" is the current user
            VIEW_TYPE_MESSAGE_SENT
        } else {
            VIEW_TYPE_MESSAGE_RECEIVED
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return if (viewType == VIEW_TYPE_MESSAGE_SENT) {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.item_message_sent, parent, false)
            SentMessageViewHolder(view)
        } else {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.item_message_received, parent, false)
            ReceivedMessageViewHolder(view)
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val message = messages[position]
        when (holder.itemViewType) {
            VIEW_TYPE_MESSAGE_SENT -> (holder as SentMessageViewHolder).bind(message)
            VIEW_TYPE_MESSAGE_RECEIVED -> (holder as ReceivedMessageViewHolder).bind(message, doctorAvatarName)
        }
    }

    override fun getItemCount() = messages.size

    inner class SentMessageViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val messageText: TextView = itemView.findViewById(R.id.text_message_body)
        val messageTime: TextView = itemView.findViewById(R.id.text_message_time)

        fun bind(message: Message) {
            messageText.text = message.content
            messageTime.text = SimpleDateFormat("HH:mm", Locale.getDefault()).format(Date(message.timestamp))
        }
    }

    inner class ReceivedMessageViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val messageText: TextView = itemView.findViewById(R.id.text_message_body)
        val messageTime: TextView = itemView.findViewById(R.id.text_message_time)
        val avatar: CircleImageView = itemView.findViewById(R.id.image_message_profile)

        fun bind(message: Message, doctorAvatarName: String) {
            messageText.text = message.content
            messageTime.text = SimpleDateFormat("HH:mm", Locale.getDefault()).format(Date(message.timestamp))
            // Load doctor avatar from drawable
            val resId = itemView.context.resources.getIdentifier(
                doctorAvatarName, "drawable", itemView.context.packageName)
            if (resId != 0) {
                avatar.setImageResource(resId)
            } else {
                avatar.setImageResource(R.drawable.me) // fallback placeholder
            }
        }
    }
} 